package com.inossem.utils.chart;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.TextView;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.Gson;
import com.inossem.utils.R;
import com.inossem.utils.log.LogUtils;

import java.util.ArrayList;
import java.util.List;

public class ChartActivity extends Activity {

    private CombinedChart combinedChart;

    private TextView title;

    private ChartBean chartBean;

    private String selectClassName;

    private List<ChartBean.ChartInfoListBean> barChartInfoList, lineChartInfoList;

    private List<ChartBean.YLimitLineBean> leftYLimitLineList, rightYLimitLineList;

    private ChartUtils chartUtils;

    private XAxis xAxis;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        setContentView(R.layout.utils_activity_chart);
        combinedChart = (CombinedChart) this.findViewById(R.id.combinedChart);
        title = (TextView) this.findViewById(R.id.title);
    }

    private void initData() {
        //初始化图表数据
        initChartData();
        //初始化分类
        initClassification();
        //初始化图表
        initChart();
    }

    private void initClassification() {
        List<ChartBean.ChartInfoListBean> allChartInfoList = chartBean.getChart_info_list();
        barChartInfoList = new ArrayList<>();
        lineChartInfoList = new ArrayList<>();
        for (int i = 0; i < allChartInfoList.size(); i++) {
            ChartBean.ChartInfoListBean chartInfoItem = allChartInfoList.get(i);
            chartInfoItem.setIndex(i);
            if (ChartUtils.TYPE_BAR.equals(chartInfoItem.getType())) {
                barChartInfoList.add(chartInfoItem);
            } else if (ChartUtils.TYPE_LINE.equals(chartInfoItem.getType())) {
                lineChartInfoList.add(chartInfoItem);
            }
        }

        List<ChartBean.YLimitLineBean> allYLimitLineList = chartBean.getY_limit_line();
        leftYLimitLineList = new ArrayList<>();
        rightYLimitLineList = new ArrayList<>();
        for (int i = 0; i < allYLimitLineList.size(); i++) {
            ChartBean.YLimitLineBean yLimitLineItem = allYLimitLineList.get(i);
            if (ChartUtils.DEPENDENCE_LEFT.equals(yLimitLineItem.getDependence())) {
                leftYLimitLineList.add(yLimitLineItem);
            } else if (ChartUtils.DEPENDENCE_RIGHT.equals(yLimitLineItem.getDependence())) {
                rightYLimitLineList.add(yLimitLineItem);
            }
        }
    }

    private void initChartData() {
        Gson gson = new Gson();
        chartBean = gson.fromJson(getIntent().getStringExtra(ChartUtils.KEY_INFORMATION), ChartBean.class);
        selectClassName = getIntent().getStringExtra(ChartUtils.KEY_SELECT_CLASS_NAME);
        chartUtils = new ChartUtils();
        title.setText(chartBean.getTitle());
    }

    private void initChart() {
        //设置描述文本
        combinedChart.getDescription().setEnabled(false);
        //是否显示表格颜色
        combinedChart.setDrawGridBackground(false);
        //是否显示阴影,在柱形图的上边补齐
        combinedChart.setDrawBarShadow(false);
        //如果20多个条目显示在图表,drawn没有值
        combinedChart.setMaxVisibleValueCount(20);
        //扩展现在只能分别在x轴和y轴
        combinedChart.setPinchZoom(false);
        // draw bars behind lines
        combinedChart.setDrawOrder(new CombinedChart.DrawOrder[]{
                CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.LINE
        });

        xAxis = combinedChart.getXAxis();
        //不显示虚线
        xAxis.setDrawGridLines(false);
        //X轴信息位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//下边显示
        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(chartBean.getX_axis_list().size());
        xAxis.setGranularity(1f);
        xAxis.setCenterAxisLabels(true);
        xAxis.setValueFormatter(new ChartXAxisValueFormatter(chartBean));
        for (int i = 0; i < chartBean.getX_limit_line().size(); i++) {
            ChartBean.XLimitLineBean xlimitLine = chartBean.getX_limit_line().get(i);
            //初始化一个限制线
            LimitLine xAxisLine = new LimitLine(Float.parseFloat(xlimitLine.getIndex()), xlimitLine.getTitle());
            //设置限制线宽度
            xAxisLine.setLineWidth(1.5f);
            //设置限制线虚线和间隔长度
            xAxisLine.enableDashedLine(10f, 10f, 0f);
            //设置限制线名称显示位置
            xAxisLine.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
            //设置限制线名称字体大小
            xAxisLine.setTextSize(10f);
            //为X轴添加限制线
            xAxis.addLimitLine(xAxisLine);
        }

        YAxis leftAxis = combinedChart.getAxisLeft();
        //不显示虚线
        leftAxis.setDrawGridLines(false);
        leftAxis.setAxisMinimum(0f);
        if (!TextUtils.isEmpty(chartBean.getLeft_axis_max_value())) {
            leftAxis.setAxisMaximum(Float.parseFloat(chartBean.getLeft_axis_max_value()));
        } else {
            leftAxis.setAxisMaximum(0f);
        }
        leftAxis.setGranularity(1f);
        leftAxis.setValueFormatter(new LeftYAxisValueFormatter(chartBean));
        for (int i = 0; i < leftYLimitLineList.size(); i++) {
            ChartBean.YLimitLineBean ylimitLine = leftYLimitLineList.get(i);
            LimitLine yAxisLine = new LimitLine(Float.parseFloat(ylimitLine.getYAxisValue()), ylimitLine.getTitle());
            yAxisLine.setLineWidth(1.5f);
            yAxisLine.enableDashedLine(10f, 10f, 0f);
            yAxisLine.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
            yAxisLine.setTextSize(10f);
            //为Y轴添加限制线
            leftAxis.addLimitLine(yAxisLine);
        }

        YAxis rightAxis = combinedChart.getAxisRight();
//        //不显示虚线
//        rightAxis.setDrawGridLines(false);
        rightAxis.setAxisMinimum(0f);
        if (!TextUtils.isEmpty(chartBean.getRight_axis_max_value())) {
            rightAxis.setAxisMaximum(Float.parseFloat(chartBean.getRight_axis_max_value()));
        } else {
            rightAxis.setAxisMaximum(0f);
        }
        rightAxis.setGranularity(1f);
        rightAxis.setValueFormatter(new RightYAxisValueFormatter(chartBean));
        for (int i = 0; i < rightYLimitLineList.size(); i++) {
            ChartBean.YLimitLineBean ylimitLine = rightYLimitLineList.get(i);
            LimitLine yAxisLine = new LimitLine(Float.parseFloat(ylimitLine.getYAxisValue()), ylimitLine.getTitle());
            yAxisLine.setLineWidth(1.5f);
            yAxisLine.enableDashedLine(10f, 10f, 0f);
            yAxisLine.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
            yAxisLine.setTextSize(10f);
            //为Y轴添加限制线
            rightAxis.addLimitLine(yAxisLine);
        }

        CombinedData combinedData = new CombinedData();
        //设置线形图
        combinedData.setData(initLineData());
        //设置柱状图
        combinedData.setData(initBarData());

        combinedChart.setData(combinedData);
        //设置XY轴方向动画
        combinedChart.animateY(2000);

        Legend legend = combinedChart.getLegend();
        //设置标题前的颜色块大小
        legend.setFormSize(9f);
        //设置标题大小
        legend.setTextSize(10f);
        //设置标题可以换行
        legend.setWordWrapEnabled(true);
        legend.setXEntrySpace(4f);

        combinedChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry entry, Highlight h) {
                if (entry.getData() != null && !TextUtils.isEmpty(selectClassName)) {
                    Intent intent = new Intent();
                    intent.setClassName(ChartActivity.this, selectClassName);
                    intent.putExtra(ChartUtils.KEY_PRIMARY_KEY, (String) entry.getData());
                    ChartActivity.this.startActivity(intent);
                }
            }

            @Override
            public void onNothingSelected() {

            }
        });
    }

    private LineData initLineData() {
        if (lineChartInfoList == null || lineChartInfoList.isEmpty()) {
            return new LineData();
        } else {
            List<ChartBean.XAxisListBean> xAxisList = chartBean.getX_axis_list();
            List<LineDataSet> lineDataSetList = new ArrayList<>();
            for (int i = 0; i < lineChartInfoList.size(); i++) {
                ChartBean.ChartInfoListBean lineChartInfoItem = lineChartInfoList.get(i);
                int index = lineChartInfoItem.getIndex();
                ArrayList<Entry> lineEntryList = new ArrayList<>();
                for (int j = 0; j < xAxisList.size(); j++) {
                    lineEntryList.add(new Entry(j + 0.5f, Float.parseFloat(xAxisList.get(j).getYAxisValueList().get(index).getYAxisValue()), xAxisList.get(j).getYAxisValueList().get(index).getPrimary_key()));
                }
                LineDataSet lineDataSet = new LineDataSet(lineEntryList, lineChartInfoItem.getName());
                lineDataSet.setColor(chartUtils.getDefaultColor());
                lineDataSet.setValueTextSize(10f);
                lineDataSet.setAxisDependency(ChartUtils.DEPENDENCE_LEFT.equals(lineChartInfoItem.getDependence()) ? YAxis.AxisDependency.LEFT : YAxis.AxisDependency.RIGHT);
                lineDataSetList.add(lineDataSet);
            }
            LineData lineData = new LineData(lineDataSetList.toArray(new LineDataSet[lineChartInfoList.size()]));
            return lineData;
        }
    }

    private BarData initBarData() {
        if (barChartInfoList == null || barChartInfoList.isEmpty()) {
            return new BarData();
        } else {
            List<ChartBean.XAxisListBean> xAxisList = chartBean.getX_axis_list();
            List<BarDataSet> barDataSetList = new ArrayList<>();
            for (int i = 0; i < barChartInfoList.size(); i++) {
                ChartBean.ChartInfoListBean barChartInfoItem = barChartInfoList.get(i);
                int index = barChartInfoItem.getIndex();
                ArrayList<BarEntry> barEntryList = new ArrayList<>();
                for (int j = 0; j < xAxisList.size(); j++) {
                    barEntryList.add(new BarEntry(j, Float.parseFloat(xAxisList.get(j).getYAxisValueList().get(index).getYAxisValue()), xAxisList.get(j).getYAxisValueList().get(index).getPrimary_key()));
                }
                BarDataSet barDataSet = new BarDataSet(barEntryList, barChartInfoItem.getName());
                barDataSet.setColor(chartUtils.getDefaultColor());
                barDataSet.setValueTextSize(10f);
                barDataSet.setAxisDependency(ChartUtils.DEPENDENCE_LEFT.equals(barChartInfoItem.getDependence()) ? YAxis.AxisDependency.LEFT : YAxis.AxisDependency.RIGHT);
                barDataSetList.add(barDataSet);
            }
            float groupSpace = ChartUtils.DEFULT_GROUP_SPACE;
            float barSpace = ChartUtils.DEFULT_BAR_SPACE;
            float barWidth = ChartUtils.getBarWidth(barChartInfoList.size(), groupSpace);
            BarData barData = new BarData(barDataSetList.toArray(new BarDataSet[barChartInfoList.size()]));
            if (barDataSetList.size() == 1) {

            } else {
                barData.setBarWidth(barWidth);
                barData.groupBars(0, groupSpace, barSpace); // start at x = 0
            }
            return barData;
        }
    }

}
